<template>
    <div>
        新增用户
        <el-form ref="form" :model="form" label-width="80px">

            <el-form-item label="用户名">
                <el-input v-model="form.username"></el-input>
            </el-form-item>
            <el-form-item label="密码">
                <el-input v-model="form.password"></el-input>
            </el-form-item>

            <el-form-item label="电话">
                <el-input v-model="form.phone"></el-input>
            </el-form-item>

            <el-form-item label="状态">
                <el-radio-group v-model="form.status">
                    <el-radio label="1">可用</el-radio>
                    <el-radio label="0">禁用</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="角色">
                <el-select v-model="selectRoleIds" multiple placeholder="请选择">
                    <el-option v-for="item in roles" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>


            <el-form-item>
                <el-button type="primary" @click="onSubmit">立即创建</el-button>
                <router-link to="/home/user">
                    <el-button> 取消 </el-button>
                </router-link>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>

import { getRoleList } from '@/api/role.js'
import { addUser } from '@/api/user.js'

export default {
    data() {
        return {
            form: {
                username: '',
                password: '',
                phone: '',
                status: '',
                roles: []
            },
            // 查询到的角色列表
            roles: [],
            selectRoleIds: []
        }
    },
    methods: {
        onSubmit() {
            for (let i = 0; i < this.selectRoleIds.length; i++) {
                let obj = { roleId: this.selectRoleIds[i] }
                this.form.roles.push(obj)
            }

            addUser(this.form).then((result) => {
                this.$message.success('新增成功')
                this.$router.push('/home/user')
            }).catch((err) => {

            });
        }
    },
    mounted() {
        // 获取角色列表
        getRoleList().then((result) => {
            this.roles = result.data.map(function (obj) {
                return { value: obj.roleId, label: obj.roleName };
            });
        }).catch((err) => {

        });
    }
}
</script>

<style>